<style lang="less" scoped>
  .table__con {
    position: relative;
    .table--add {
      position: absolute;
      right: 0;
      top: 2px;
      z-index: 999;
    }
  }
</style>
<template>
  <el-dialog :visible.sync="currentShowFlag" append-to-body fullscreen :close-on-click-modal="false" :close-on-press-escape="false" @open="handleDialogOpen" @closed="handleDialogClosed">
    <div slot="title" class="detail-dialog__header">{{$t('system_role.detailDialog')}}</div>
    <div>
      <simple-form ref="form" v-model="formModel" label-width="80px" :form-field="formField" :grid="{xs: 12, sm: 12, md: 8}" :view-flag="viewFlag"></simple-form>
      <div class="table__con">
        <el-button v-if="!viewFlag && tabValue === 'second'" type="primary" @click="handleDatascopeAddClick" class="table--add">{{$t('operation.create')}}</el-button>
        <el-tabs v-model="tabValue">
          <el-tab-pane :label="$t('system_role.tabTitle')" name="first" :style="{height: containerHeight, overflow: 'auto'}">
            <el-tree ref="permissionTree" node-key="id" :data="menuTreeData" :props="{ children: 'children', label: 'title' }" show-checkbox></el-tree>
          </el-tab-pane>
          <el-tab-pane :label="$t('system_role.datascopeTabTitle')" name="second" :style="{height: containerHeight}">
            <simple-table :table-column="tableColumn" :table-data="tableData" :pageable="false">
              <template slot-scope="scope" slot="controllerId">
                <form-component :view-flag="tableColumnSlot.viewFlag" :form-item="tableColumnSlot.controllerId" v-model="scope.row"></form-component>
              </template>
              <template slot-scope="scope" slot="tableId">
                <form-component :view-flag="tableColumnSlot.viewFlag" :form-item="tableColumnSlot.tableId" v-model="scope.row"></form-component>
              </template>
              <template slot-scope="scope" slot="columnId">
                <form-component :view-flag="tableColumnSlot.viewFlag" :form-item="tableColumnSlot.columnId" v-model="scope.row"></form-component>
              </template>
              <template slot-scope="scope" slot="attrInUser">
                <form-component :view-flag="tableColumnSlot.viewFlag" :form-item="tableColumnSlot.attrInUser" v-model="scope.row"></form-component>
              </template>
              <template slot-scope="scope" slot="methodId">
                <form-component :view-flag="tableColumnSlot.viewFlag" :form-item="tableColumnSlot.methodId" v-model="scope.row"></form-component>
              </template>
              <template slot-scope="scope" slot="tableAlias">
                <form-component :view-flag="tableColumnSlot.viewFlag" :form-item="tableColumnSlot.tableAlias" v-model="scope.row"></form-component>
              </template>
              <template slot-scope="scope" slot="value">
                <form-component :view-flag="tableColumnSlot.viewFlag" :form-item="tableColumnSlot.value" v-model="scope.row"></form-component>
              </template>
              <template slot-scope="scope" slot="oper">
                <form-component :view-flag="tableColumnSlot.viewFlag" :form-item="tableColumnSlot.oper" v-model="scope.row"></form-component>
              </template>
              <template slot-scope="scope" slot="valueType">
                <form-component :view-flag="tableColumnSlot.viewFlag" :form-item="tableColumnSlot.valueType" v-model="scope.row"></form-component>
              </template>
              <template slot-scope="scope" slot="status">
                <form-component :view-flag="tableColumnSlot.viewFlag" :form-item="tableColumnSlot.status" v-model="scope.row"></form-component>
              </template>
              <template slot="operation" slot-scope="scope">
                <el-button circle @click="handleDatascopeDelClick(scope.$index)" icon="el-icon-delete" :title="$t('operation.delete')"></el-button>
              </template>
            </simple-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div slot="footer">
      <el-button @click="handleDialogClose">{{viewFlag ? $t('operation.close') : $t('operation.cancel')}}</el-button>
      <el-button type="primary" @click="handleDataSubmit" v-if="!viewFlag">{{$t('operation.submit')}}</el-button>
    </div>
  </el-dialog>
</template>
<script>
import Axios from 'axios'
const BASEURL = {
  get: '/api/system/role/get',
  save: '/api/system/role/save',
  update: '/api/system/role/update',
  // 菜单树形结构
  menu: '/api/system/menu/treeData'
}
export default {
  name: 'sys_role_detail',
  data () {
    return {
      tabValue: 'first',
      formModel: { status: 'Y' },
      menuTreeData: [],
      tableData: [],
      containerHeight: '0px',
      checkedKeys: []
    }
  },
  inject: ['handleDataSearch'],
  computed: {
    currentShowFlag: {
      get () { return this.showFlag },
      set (val) { this.$emit('update:showFlag', val) }
    },

    status () { return this.$getDictList('data_status') },

    formField () {
      return [
        {
          prop: 'name',
          label: this.$t('system_role.name'),
          type: 'Input',
          rules: { trigger: 'blur', message: this.$t('validate.notBlank'), required: true }
        },
        {
          prop: 'status',
          label: this.$t('system_role.status'),
          type: 'RadioGroup',
          component: { optionList: this.status }
        },
        {
          prop: 'remarks',
          label: this.$t('system_role.remarks'),
          type: 'Input',
          component: { type: 'textarea' },
          col: { xs: 24, sm: 24, md: 24 }
        }
      ]
    },

    tableColumn () {
      let baseTableColumn = [
        { prop: 'controller.id', label: this.$t('system_role.datascope.controller'), width: 250, slotName: 'controllerId' },
        { prop: 'method.id', label: this.$t('system_role.datascope.method'), width: 250, slotName: 'methodId' },
        { prop: 'table.id', label: this.$t('system_role.datascope.table'), width: 120, slotName: 'tableId' },
        { prop: 'tableAlias', label: this.$t('system_role.datascope.tableAlias'), width: 100, slotName: 'tableAlias' },
        { prop: 'attrInUser', label: this.$t('system_role.datascope.attrInUser'), width: 120, slotName: 'attrInUser' },
        { prop: 'column.id', label: this.$t('system_role.datascope.column'), width: 80, slotName: 'columnId' },
        { prop: 'valueType', label: this.$t('system_role.datascope.valueType'), width: 150, slotName: 'valueType' },
        { prop: 'operation', label: this.$t('system_role.datascope.operation'), width: 60, slotName: 'oper' },
        { prop: 'value', label: this.$t('system_role.datascope.value'), width: 150, slotName: 'value' },
        { prop: 'status', label: this.$t('system_role.datascope.status'), width: 60, slotName: 'status' }
      ]
      if (this.viewFlag) return baseTableColumn
      else {
        return baseTableColumn.concat([{ label: this.$t('field.operation'), slotName: 'operation', width: 60, fixed: 'right' }])
      }
    },

    tableColumnSlot () {
      return {
        viewFlag: this.viewFlag,
        controllerId: {
          prop: 'controllerId',
          type: 'Input'
        },
        methodId: {
          prop: 'methodId',
          type: 'Input'
        },
        columnId: {
          prop: 'columnId',
          type: 'Input'
        },
        tableId: {
          prop: 'tableId',
          type: 'Input'
        },
        tableAlias: {
          prop: 'tableAlias',
          type: 'Input'
        },
        attrInUser: {
          prop: 'attrInUser',
          type: 'Input'
        },
        value: {
          prop: 'value',
          type: 'Input'
        },
        oper: {
          prop: 'operation',
          type: 'Input'
        },
        valueType: {
          prop: 'valueType',
          type: 'Input'
        },
        status: {
          prop: 'status',
          type: 'Input'
        }
      }
    }
  },
  props: {
    showFlag: { type: Boolean, default: false },
    viewFlag: { type: Boolean },
    detailData: { type: Object }
  },
  methods: {
    handleDialogClose () {
      this.currentShowFlag = false
    },

    handleDataSubmit () {
      this.$refs.form.$refs.simpleForm.validate(status => {
        if (status) {
          let loadingFlag = this.$loading({ target: this.$el.querySelector('.el-dialog') })
          let submitModel = this.$_.cloneDeep(this.formModel)

          let checkedNodes = this.$refs['permissionTree'].getCheckedNodes()
          let halfCheckedNodes = this.$refs['permissionTree'].getHalfCheckedNodes()
          let permissionNodes = checkedNodes.concat(halfCheckedNodes, { id: 'root_id' })
          submitModel.menuList = permissionNodes

          submitModel.sysDataPermissionList = this.tableData.map(item => {
            item.controller = { id: item.controllerId }
            item.method = { id: item.methodId }
            item.column = { id: item.columnId }
            item.table = { id: item.tableId }
            return item
          })

          this.$axios
            .post(this.detailData.id ? BASEURL.update : BASEURL.save, submitModel)
            .then(resp => {
              this.currentShowFlag = false
              this.$message({ type: 'success', message: this.$t('tip.saveSuccess') })
              this.handleDataSearch()
            })
            .finally(() => {
              loadingFlag.close()
            })
        }
      })
    },

    handleDialogOpen () {
      this.$nextTick(() => {
        this.calTableHeight()
      })

      if (!this.detailData.id) {
        let loadingFlag = this.$loading({ target: this.$el.querySelector('.el-dialog') })
        this.$axios
          .post(BASEURL.menu, {})
          .then(resp => {
            let respData = resp.data
            this.menuTreeData = respData.children
          })
          .finally(() => {
            loadingFlag.close()
          })

        return
      }

      let requestList = [this.$axios.post(BASEURL.menu, {}), this.$axios.post(BASEURL.get, { id: this.detailData.id })]
      let loadingFlag = this.$loading({ target: this.$el.querySelector('.el-dialog') })
      Axios
        .all(requestList)
        .then(Axios.spread((menuResp, resp) => {
          let respData = resp.data
          this.formModel = respData

          let menuRespData = menuResp.data
          this.menuTreeData = menuRespData.children

          this.tableData = respData.sysDataPermissionList.map(item => {
            item.controllerId = item.controller.id
            item.methodId = item.method.id
            item.tableId = item.table.id
            item.columnId = item.column.id
            return item
          })

          this.checkedKeys.splice(0)
          this.menuTreeData.forEach(menuItem => {
            this.getCheckedKeys(menuItem)
          })

          this.$refs['permissionTree'].setCheckedKeys(this.checkedKeys)
        }))
        .finally(() => {
          loadingFlag.close()
        })
    },

    getCheckedKeys (menuItem) {
      if (this.formModel.menuList && this.formModel.menuList.map(menuListItem => menuListItem.id).indexOf(menuItem.id) >= 0) {
        if (menuItem.children && menuItem.children.length > 0) {

        } else {
          this.checkedKeys.push(menuItem.id)
        }
      }

      if (menuItem.children && menuItem.children.length > 0) {
        menuItem.children.forEach((item) => {
          this.getCheckedKeys(item)
        })
      }
    },

    calTableHeight () {
      let mainHeight = this.$el.querySelector('.el-dialog__body').offsetHeight - 20
      let formHeight = this.$el.querySelector('.el-form').offsetHeight
      // dialog内容总高度 - 表单高度 - tabbar高度
      this.containerHeight = mainHeight - formHeight - 55 + 'px'
    },

    // 数据权限新增一行
    handleDatascopeAddClick () {
      this.tableData.push({})
    },

    handleDatascopeDelClick (idx) {
      this.tableData.splice(idx, 1)
    },

    handleDialogClosed () {
      this.$refs.form.resetFields()
      this.menuTreeData.splice(0)
      this.tabValue = 'first'
      this.$refs['permissionTree'].setCheckedKeys([])
      this.tableData.splice(0)
      this.formModel = { status: 'Y' }
    }
  }
}
</script>
